package cn.laixueit.cart.interceptor;

import cn.laixueit.cart.config.JwtProperties;
import cn.laixueit.entity.UserInfo;
import cn.laixueit.utils.CookieUtils;
import cn.laixueit.utils.JwtUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties properties;

    // 定义一个线程域，存放登录用户
    private static final ThreadLocal<UserInfo> tl = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取cookie中的token
        String token = CookieUtils.getCookieValue(request, properties.getCookieName());

        // 未登录，无法获取token
        if(StringUtils.isBlank(token)){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return  false;
        }

        // 登录成功，解析token

        UserInfo userInfo = JwtUtils.getInfoFromToken(token, properties.getPublicKey());
        tl.set(userInfo);
        return true;
    }


    /**
     * 单独定义一个从thread中获取用户信息的犯法
     * @return
     */
    public static  UserInfo getLogin(){
        return tl.get();
    }


}
